// server > utils > jwt.js
const jwt = require('jsonwebtoken')
const util = require('util')
const skipList = require('@/utils/jwt/jwt_skip_list') // 跳过校验api
const jwtverify = util.promisify(jwt.verify)

// sign用于生成token
const sign = (option, time = 3600) => {
  return jwt.sign(option, 'your_secret', {
    expiresIn: time, // 当前设定过期时间在3600秒之后
  })
}


// 校验
let verify = () => async (ctx, next) => {
  let skip_index = skipList.findIndex(val => {
    let reg = new RegExp(val)
    return reg.test(ctx.url.split('?')[0])
  })
  if (skip_index != -1) return await next()
  let jwtToken = ctx.request.headers.token // 获取到前端传递多来的token
  if (jwtToken) {
    // 校验token的合法性
    try {
      let res = await jwtverify(jwtToken, 'your_secret')
      ctx.request.headers.u_tk = res.u_tk
      await next()
    } catch (err) {
      ctx.body = {
        code: 401,
        data: '',
        msg: 'token失效',
      }
    }
  } else {
    ctx.body = {
      code: 402,
      data: '',
      message: 'token参数缺失',
    }
  }
}

module.exports = {
  sign,
  verify,
}
